package com.xxl.job.admin.core.model;

import com.baomidou.mybatisplus.annotation.TableField;
import com.xxl.job.admin.core.conf.XxlJobAdminConfig;
import org.springframework.util.StringUtils;

/**
 * @author xuxueli 2019-05-04 16:43:12
 */
public class XxlJobUser {
	
	private int id;
	private String username;		// 账号
	private String password;		// 密码
	private int role;				// 角色：0-普通用户、1-管理员
	private String permission;	// 权限：执行器ID列表，多个逗号分割
	private String tenantId;

	@TableField(exist = false)
	private boolean tenantSwitchOpen;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public int getRole() {
		return role;
	}

	public void setRole(int role) {
		this.role = role;
	}

	public String getPermission() {
		return permission;
	}

	public void setPermission(String permission) {
		this.permission = permission;
	}

	public String getTenantId() {
		return tenantId;
	}

	public void setTenantId(String tenantId) {
		this.tenantId = tenantId;
	}

	public boolean isTenantSwitchOpen() {
		return XxlJobAdminConfig.getAdminConfig().isTenantSwitchOpen();
	}

	public boolean validReadPermission(int jobGroup){

		String permission = getJobGroupPermission(jobGroup);
		if("e".equals(permission) || "r".equals(permission)){
			return true;
		}else {
			return false;
		}
	}

	public boolean validEditPermission(int jobGroup){
		String permission = getJobGroupPermission(jobGroup);
		if("e".equals(permission)){
			return true;
		}else {
			return false;
		}

	}

	public String getJobGroupPermission(int jobGroup) {
		if (this.role == 1) {
			return "e";
		} else {
			if (StringUtils.hasText(this.permission)) {
				for (String permissionItem : this.permission.split(",")) {
					String permissionGroup = permissionItem;
					//默认是只读权限
					String permission = "r";
					if (permissionItem.indexOf(":") > 0) {
						permissionGroup = permissionItem.substring(0, permissionItem.indexOf(":"));
						if (permissionItem.indexOf(":") + 1 < permissionItem.length()) {
							permission = permissionItem.substring(permissionItem.indexOf(":") + 1);
						}

					}
					if (String.valueOf(jobGroup).equals(permissionGroup)) {
						return permission;
					}
				}
			}
			//无权限
			return "n";
		}
	}

}
